import flet as ft
from tools.file_utils import remove_part_from_filenames


class FileToolsUI:
    def __init__(self, page, show_main_menu):
        self.page = page
        self.show_main_menu = show_main_menu
        self.setup_ui()

    def setup_ui(self):
        # 文件路径输入框
        self.dir_path = ft.TextField(label="目录路径", hint_text="请输入目录路径")
        self.part_to_remove = ft.TextField(
            label="要删除的部分", hint_text="请输入要删除的部分"
        )

        # 执行按钮
        self.run_button = ft.ElevatedButton(
            text="执行",
            on_click=self.on_run_button_click,
        )

        # 返回主菜单按钮
        self.back_button = ft.ElevatedButton(
            text="返回主菜单",
            on_click=lambda e: self.show_main_menu(),  # 使用 lambda 忽略事件参数
        )

        # 结果输出
        self.result_text = ft.Text()

    def build(self):
        return ft.Column(
            controls=[
                ft.Text("文件工具", size=20),
                self.dir_path,
                self.part_to_remove,
                self.run_button,
                self.back_button,
                self.result_text,
            ],
            spacing=20,
        )

    def on_run_button_click(self, e):
        dir_path = self.dir_path.value
        part_to_remove = self.part_to_remove.value

        if not dir_path or not part_to_remove:
            self.result_text.value = "请输入目录路径和要删除的部分！"
            self.page.update()
            return

        try:
            result = remove_part_from_filenames(dir_path, part_to_remove)
            self.result_text.value = f"操作成功：\n{result}"
        except Exception as ex:
            self.result_text.value = f"操作失败：{str(ex)}"

        self.page.update()
